<?php
namespace Tongcheng\Controller;
use Think\Controller;
header("Content-type: text/html; charset=utf-8");
class WithdrawController extends CommonController {
    //商家提现审核页面
    public function index(){
        $search = I('search');
        $wid = session('wid');
        $status = I('status');
        $count = M('withdraw')
            ->alias('wd')
            ->join('tp_wechat w on w.wid = wd.wid')
            ->join('tp_shop s on s.shop_id = wd.shop_id')
            ->where(array('wd.wid'=>$wid , 'wd.status' => $status))
            ->where(['s.name | wd.alipay | wd.wx | wd.bankcard' => ['like', '%'.$search.'%']])
            ->count();
        $page = new \Think\Page($count, 20);
        $show = $page->show();
        $info = M('withdraw')
            ->alias('wd')
            ->field('wd.*,w.withdraw_rate,s.name as sname')
            ->join('tp_wechat w on w.wid = wd.wid')
            ->join('tp_shop s on s.shop_id = wd.shop_id')
            ->where(array('wd.wid'=>$wid , 'wd.status' => $status))
            ->where(['s.name | wd.alipay | wd.wx | wd.bankcard' => ['like', '%'.$search.'%']])
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
        $this->assign('status',$status);
        $this->assign('info',$info);
        $this->assign('show',$show);
        $this->assign('search',$search);
        $this->assign('count',$count);
        $this->display();
    }

    //确认审核
    public function commit () {
        $id = I('id');
        $wid = session('wid');
        $date = date('Y-m-d H:i:s', time());
        $info = M('withdraw')->alias('w')->field('w.*,s.openid')->where(['w.id' => $id, 'w.wid' => $wid])->join('tp_shop s on s.shop_id =w.shop_id')->find();
        $row = M('withdraw')->where(['id' => $id, 'wid' => $wid])->save(['status' => 1]);

        //var_dump($info);exit;
        if($row && $info){
        //if( $info){

        }

        $this->ajaxReturn($row?1:0);
    }
    protected function build_order_no(){
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
    //拒绝
    public function refuse () {
        $id = I('id');
        $wid = session('wid');
        $row = M('withdraw')->where(['id' => $id, 'wid' => $wid])->save(['status' => 3]);
        if ($row) {
            //返钱
            $list = M('withdraw')->field('apply_money, shop_id')->where(['id' => $id, 'wid' => $wid])->find();
            $shopOldMoney = M('shop')->field('money')->where(['shop_id' => $list['shop_id']])->find();
            $money = (int)$list['apply_money'] + (int)$shopOldMoney['money'];
            $rowMoney = M('shop')->where(['shop_id' => $list['shop_id']])->save(['money' => $money]);
            if ($rowMoney) {
                $this->ajaxReturn(true);
            } else {
                M('withdraw')->where(['id' => $id, 'wid' => $wid])->save(['status' => 0]);
                $this->ajaxReturn(false);
            }
        } else {
            $this->ajaxReturn(false);
        }
    }

    //确认打款
    public function addMoney () {
        vendor('Weixinpay.WxRefund');
        M()->startTrans();
        $id = I('id');
        $wid = session('wid');
        $date = date('Y-m-d H:i:s', time());
        $info = M('withdraw')->alias('w')->field('w.*,s.openid')->where(['w.id' => $id, 'w.wid' => $wid])->join('tp_shop s on s.shop_id =w.shop_id')->find();

        //退款及发送消息
        $map['wid'] = $wid;
        $wechat = M("Wechat")->where($map)->find();
        $mchid = $wechat['mch_id'];                 //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
        $appid = $wechat['appid'];                  //微信支付申请对应的公众号的APPID
        $appKey = $wechat['app_secret'];            //微信支付申请对应的公众号的appsecret
        $apiKey = $wechat['partner_key'];           //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
        $openId = $info['openid'];                  //获取openid
        $wxpay = new \Wxrefund();
        //①、获取当前访问页面的用户openid（如果给指定用户转账，则直接填写指定用户的openid)
        $wxPay = new \WxRefund($mchid,$appid,$appKey,$apiKey);
        if(!$openId) exit('获取openid失败');
        //②、付款
        $outTradeNo = $this->build_order_no();      //订单号
        $payAmount = $info['real_money'];           //转账金额，单位:元。转账最小金额为1元
        $trueName = $info['name'];                  //收款人真实姓名

        $result = $wxPay->createJsBizPackage($openId,$payAmount,$outTradeNo,$trueName);
        //var_dump($result);
        //成功
        if($result['result_code'] == "SUCCESS" && $result['return_code'] == "SUCCESS"){
            //发送模板消息
            $a = sendWithdrawMessage($info['openid'],$id);
            //将返回存入数据库
            $data['status'] =2;                                         //状态
            $data['partner_trade_no'] = $result['partner_trade_no'];    //自己生产的订单号
            $data['payment_no'] = $result['payment_no'];                //微信生成的订单号
            $data['remit_time'] = $result['payment_time'];              //打款时间
            $row = M('withdraw')->where(['id' => $id, 'wid' => $wid])->save($data);
            if($row && $a){
                M()->commit();
                $this->ajaxReturn("打款成功");
            }else{
                M()->rollback();
                $this->ajaxReturn("打款失败，请重试！");
            }
        }else{
            $this->ajaxReturn($result['err_code_des']);
        }


    }
}